import type from '../type'
import axios from 'axios'

const doStoreToken = (token) => {
  try {
    if (!token) {
      window.sessionStorage.removeItem('token')
    } else {
      window.sessionStorage.setItem('token', token)
    }
  } catch (e) {}
  try {
    // window.plus.storage.setItem('token', token)
  } catch (e) {}
}

let token = window.sessionStorage.getItem('token')

let match = window.location.href.match(/\??&?access_token=([\d\w]+)/)
if (match && match.length === 2) {
  doStoreToken(token = match[1])
  window.history.replaceState(null, '', window.location.href.replace(match[0], ''))
}

const PROFILE = {avatar: '', reward: 0, balance: 0, name: null}

const state = {
  pending: false,
  token: token,
  fingerprint: '',
  member: {...PROFILE},
  permission: []
}

const getters = {
  token: state => state.token,
  member: state => state.member,
  permission: state => state.permission,
  isAuthorizationPending: state => state.pending
}

const mutations = {
  [type.TokenChange] (state, token) {
    state.token = token
    if (!token) { state.member = {...PROFILE} }
    doStoreToken(token)
  },
  [type.TokenPendingChange] (state, pending) {
    state.pending = pending
  },
  [type.MemberProfileChange] (state, profile) {
    state.member = Object.assign({}, profile)
  }
}

var actions = {
  [type.MemberProfileChange] ({ commit }) {
    return axios.get(`/member/profile`)
      .then(res => {
        commit(type.MemberProfileChange, res.data)
        commit(type.TokenPendingChange, false)
        commit(type.TokenChange, res.data.token)
      })
      .catch(() => {
        commit(type.TokenPendingChange, false)
        commit(type.TokenChange, null)
      })
  }
}

export default ({
  state,
  getters,
  actions,
  mutations
})
